<?php

require_once 'dao.php';
require_once 'client.php';

/**
 * Client Data Access Object
 */
class client_dao extends dao
{
	public $key = 'client_id';
	protected $model = 'client';
	protected $table = 'clients';
	protected $tables_rel = 'contracts';
	protected $hash = 'sha512';
	
	/**
	 * Constructor for client_dao
	 *
	 * @param mysqli $db mysqli connection
	 */
	function __construct()
	{
		parent::__construct();
	}

	function fetch_all($search = false)
	{
		$clients = array();
		$sql_clients = '
			SELECT
				`clients`.`client_id`,
				`clients`.`username`,
				`clients`.`name`,
				`clients`.`email`,
				`clients`.`active`
			FROM `clients`
			LEFT JOIN `contracts` ON (
				`contracts`.`client_id` = `clients`.`client_id` ) ';
		if ($search) {
			$sql_clients .= '
				WHERE `clients`.`name` LIKE "%'.$search.'%"
				OR `clients`.`username` LIKE "%'.$search.'%"
				OR `contracts`.`ip` LIKE "%'.$search.'%" ';
		}
		$sql_clients .= 'GROUP BY `clients`.`client_id`';
		$result_clients = $this->db->query($sql_clients);
		while ($client = $result_clients->fetchObject('client')) {
			$clients[] = $client;
		}
		return $clients;
	}
	
	function activate($client_id)
	{
		$query_activate = 'UPDATE `'.$this->table.'` SET `active` = 1 WHERE `'.$this->key.'` = "'.$client_id.'"';
		if ($this->db->query($query_activate)) {
			$client->active = true;
			return true;
		} else {
			throw new Exception('couldnt_activate_client');
			return false;
		}
	}

	function disactivate($client_id)
	{
		$query_disactivate = 'UPDATE `'.$this->table.'` SET `active` = 0 WHERE `'.$this->key.'` = "'.$client_id.'"';
		if ($this->db->query($query_disactivate)) {
			$this->active = false;
			return true;
		} else {
			throw new Exception('couldnt_disactivate_client');
		}
	}

	function update_password(&$client,$password)
	{
		$sql_update_password = '
			UPDATE `clients`
			SET `password` = "'.hash('sha512', $password).'"
			WHERE `client_id` = "'.$client->client_id.'"';
		if (!$this->db->query($sql_update_password)) {
			throw new Exception('password_not_saved');
			return false;
		}
		return true;
	}
	
	function verify_password(&$client,$password1)
	{
		$sql_password2 = '
			SELECT `password`
			FROM `'.$this->table.'`
			WHERE `'.$this->key.'` = "'.$this->key.'"';
		if (!$result_password2 = $this->db->query($sql_password2)) {
			throw new Exception('password_query_failed');
			return false;
		} elseif (!$result_password2->num_rows) {
			throw new Exception('client_or_password_incorrect');
			return false;
		} 
		$password2 = $result_password2->fetchObject();
		if ($password2->password != $password1) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Authenticate a client
	 * 
	 * em caso que nao, tenta autenticar usando os valores no $_POST
	 * em caso que o usuario é autenticado, os dados sao guardados nas variaveis desse class
	 */
	public function auth()
	{
		if ($_POST['action'] == 'logout' || $_GET['action'] == 'logout') {
			$_SESSION = array();
			session_destroy();
			return false;
		} elseif (isset($_POST['client_username']) && isset($_POST['client_password'])) {
			$sql_client = '
				SELECT *
				FROM `'.$this->table.'`
				WHERE `username` = "'.get('client_username').'"
					AND `password` = "'.hash($this->hash, $_POST['client_password']).'"';
			$result_client = $this->db->query($sql_client);

			if ($client = $result_client->fetchObject($this->model)) {
				$_SESSION['vulpes_client_session'] = true;
				$_SESSION['vulpes_client_username'] = $client->username;
				return $client;
			} else {
				return false;
			}
		} elseif ($_SESSION['vulpes_client_session'] == true) {
			$sql_client = '
				SELECT *
				FROM `'.$this->table.'`
				WHERE `username` = "'.$_SESSION['vulpes_client_username'].'"';
			$result_client = $this->db->query($sql_client);
			if ($client = $result_client->fetchObject($this->model)) {
				return $client;
			}
		}
		return false;
	}
	
	function update_timestamp(&$client_id)
	{
		$sql_timestamp = '
			UPDATE `'.$this->table.'`
			SET `last_access` = "'.date('YmdHis').'"
			WHERE `username` = "'.$client_id.'"';
		if ($this->db->query($sql_timestamp)) return true;
		else return false;
	}
}

?>
